package com.qfedu.openplateform.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.qfedu.openplateform.cache.service.CacheService;
import com.qfedu.openplateform.common.constans.ExceptionDict;
import com.qfedu.openplateform.common.entity.ResponseData;
import com.qfedu.openplateform.gateway.config.ApplicationHolder;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenFilter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取token
        // 解析token  ----> id   sub
        // 根据 sub  得到 username  去redis 找对应的token ,进行比对，如果相同，就放行 否则拦截器


        String token = request.getParameter("token");

        if (token!=null){
            try {
                //解密token
                Claims body = Jwts.parser().setSigningKey("meiyoumima".getBytes()).parseClaimsJws(token).getBody();
                String username = body.getSubject();
                Object id = body.get("id");

                // 通过 ApplicationHolder 去容器中 获取 CacheService
                CacheService cacheService = ApplicationHolder.getApplicationContext().getBean(CacheService.class);

                String tokenFromRedis = null;

                tokenFromRedis = cacheService.getFromRedis("token-"+username);

                if(token.equals(tokenFromRedis)){// 验证tocken 成功
                    // 放行
                    return true;
                }else {
                    // 拦截 token 未被认证
                    response.setContentType("application/json;charset=utf-8");
                    ResponseData bean = new ResponseData();
                    bean.setCode(ExceptionDict.UNLOGIN);
                    bean.setMessage("尚未登陆认证");
                    try {
                        response.getWriter().println(JSON.toJSONString(bean));
                    } catch (JsonProcessingException ex) {
                        ex.printStackTrace();
                    }

                    return false;
                }

            } catch (Exception e) {
                e.printStackTrace();
                response.setContentType("application/json;charset=utf-8");
                ResponseData bean = new ResponseData();
                bean.setCode(ExceptionDict.UNLOGIN);
                bean.setMessage("登陆认证异常");
                try {
                    response.getWriter().println(JSON.toJSONString(bean));
                } catch (JsonProcessingException ex) {
                    ex.printStackTrace();
                }

            }
        }


        response.setContentType("appliaction/json;charset=utf-8");
        ResponseData bean = new ResponseData();
        bean.setCode(ExceptionDict.UNLOGIN);
        bean.setMessage("尚未拥有登陆认证");
        // 放行
        return true;


    }
}
